package main

import (
	"fmt"
	"github.com/dgraph-io/badger/v3"
)

func main() {
	//  打开DB
	db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
	defer db.Close()

	// 读写事务
	err = db.Update(func(txn *badger.Txn) error {
		txn.Set([]byte("foo"), []byte("bar"))
		txn.Get([]byte("foo"))
		return nil
	})

	// 只读事务
	err = db.View(func(txn *badger.Txn) error {
		txn.Get([]byte("foo_v1"))
		return nil
	})

	err = db.View(func(txn *badger.Txn) error {
		opts := badger.DefaultIteratorOptions
		opts.PrefetchSize = 10
		it := txn.NewIterator(opts)
		defer it.Close()

		for it.Rewind(); it.Valid(); it.Next() {
			item := it.Item()
			k := item.Key()

			err = item.Value(func(v []byte) error {
				fmt.Printf("key = %s, value = %s\n", k, v)
				return nil
			})
		}
		return nil
	})

	err = db.RunValueLogGC(0.7)
	_ = err
}
